package cn.fuxi2022.module.excel.controller;

import cn.fuxi2022.commons.redis.service.CaptchaService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.core.utils.SmsUtils;
import cn.fuxi2022.feign.api.GroupAuth;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.module.excel.config.CustomCellWriteHandler;
import cn.fuxi2022.module.excel.config.StyleStrategy;
import cn.fuxi2022.module.excel.pojo.DemoData;
import cn.fuxi2022.module.excel.service.ExcelService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("admin/excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @Autowired
    private GroupAuth groupAuth;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private SmsUtils smsUtils;

    @GetMapping("/export/captcha")
    public R refundOrderSendCaptcha(HttpServletRequest httpServletRequest) {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);

        // 发送验证码
        String captcha;
        // 1.将验证码传入redis
        if (!(StringUtils.hasText(captcha = captchaService.saveCaptcha(phone)))) {
            throw new SmartGroupException("你已经获取过验证码了，稍后再试吧");
        }

        // 2.使用短信平台发送验证码短信
        if (!smsUtils.sendCaptcha(phone, captcha, "1")) {
            throw new SmartGroupException("验证码发送失败，请检查手机号");
        }
        return R.ok("发送验证码成功");
    }

    @PostMapping("/export/{code}")
    public void export(HttpServletRequest httpServletRequest, HttpServletResponse response, @PathVariable("code") String code) throws IOException {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);

        // 判断验证码是否合法
        if (!captchaService.checkCaptcha(code, phone)) {
            throw new SmartGroupException("验证码错误，请重新输入");
        }

        // 这里是个查询列表的语句
        List<DemoData> list = excelService.getDemoList();
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("社员信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setHeader("requestType", "file");  // 自定义的header
            response.setHeader("Access-Control-Expose-Headers", "requestType"); //设置这个header 可见
            // 当前用户桌面
            // File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
            // String desktopPath = desktopDir.getAbsolutePath() + "\\导出信息.xlsx";
            EasyExcel.write(response.getOutputStream(), DemoData.class)
                    .inMemory(true) // 富文本
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 字体居中显示
                    .registerWriteHandler(new CustomCellWriteHandler()) // 自定义的样式
                    .registerWriteHandler(StyleStrategy.getStyleStrategy()) // 自定义全表的样式
                    .sheet("导出信息")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSONString(R.error("文件生成失败")));
        }
    }
}
